package com.qdxwx.manage.controller.manager;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.data.service.manager.ManagerService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.manager.ManagerRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户分配角色
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/manager")
public class ManagerAuthRoleController extends BaseController {

    @Autowired
    private ManagerService managerService;

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{managerId}")
    public String authRole(@PathVariable("managerId") int managerId, ModelMap mmap) {
        if (managerId < 1) return error404;
        Manager manager = managerService.get(managerId);
        if (manager == null) return error404;
        // 获取用户所属的角色列表
        List<ManagerRole> managerRoles = managerService.getRolesByManagerId(managerId);
        mmap.put("manager", manager);
        mmap.put("managerRoles", managerRoles);
        return "manager/auth-role";
    }

    /**
     * 用户授权角色
     */

    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole.json")
    @ResponseBody
    public AjaxResult insertAuthRole(HttpServletRequest request) {
        int managerId = TKConvert.toInteger(request.getParameter("managerId"));
        if (managerId < 1) return error("参数异常");
        Integer[] roleIds = TKConvert.toIntArray(request.getParameter("roleIds"));
        if (roleIds.length < 1) return error("至少选择一个角色");
        Manager manager = new Manager();
        manager.setManagerId(managerId);
        manager.setRoleIds(roleIds);
        managerService.insertRoles(manager);
        return success();
    }

}